<?php
/**
 * User: bgl
 * Date: 2023/6/13
 * Time: 17:44
 */

namespace App\Admin\Controllers\Products;


use App\Importer\Basics\BImporter;
use App\Models\Product\ProductSkuClassify;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class SkuClassifyUploadController extends AdminController{

    protected $title = '基础品类上传';

    protected function grid(){
        return view("products.sku-classify.upload.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importClassify(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];

            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;
            $codeArr = [];
            foreach($data as $row){
                $count++;
                $_titleCn = $row[0] ? trim($row[0]) : '';
                $_titleEn = $row[1] ? trim($row[1]) : '';
                $_code = $row[2] ? trim($row[2]) : '';
                $remark = $row[3] ? trim($row[3]) : '';

                if(!$_titleCn || !$_titleEn || !$_code){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                $code = strtoupper($_code);
                if (!preg_match("/^[A-Z]{3}$/", $code)) {
                    $errors[$count] = '品类不正确/不存在';
                    continue;
                }

                if(!in_array($code, $codeArr)){
                    $codeArr[$count] = $code;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $reCount = ProductSkuClassify::query()->where('classify_code',$code)->count();
                if($reCount > 0){
                    $errors[$count] = $code.'系统已存在';
                    continue;
                }

                DB::beginTransaction();
                $skuClassify = ProductSkuClassify::query()->create(
                    [
                        'classify_cn'   => $_titleCn,
                        'classify_en'   => $_titleEn,
                        'classify_code' => $code,
                        'remark'    => $remark,
                        'admin_id'  => $userId,
                        'status'    => ProductSkuClassify::STATUS_YES,
                    ]
                );
                if(!$skuClassify){
                    DB::rollBack();
                    continue;
                }
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
